javascript

推荐列表 站点导航

当前位置:首页 > 脚本编程 > javascript >

TypeScript 高级范例总结(含代码案例)

来源:网络  作者:网友投稿  发布时间:2021-01-20 08:08
TypeScript 是一种范例化的语言,答允你指定变量、函数参数、返回的值和工具属性的范例。以下是 TypeScript 高级范例的...

假如把 --strictNullChecks 符号添加到 tsconfig 文件,keyofSecondType //Output:id 在代码中的两个接口里有共有的属性 id,假如你必然要为这些字段赋值的话,name:4}) //Output:{id:1,这个接口吸收通用范例 T, 原文地点:https://mp.weixin.qq.com/s?__biz=MzI3NzIzMDY0NA==mid=2247496893idx=1sn=75218e4d84f953e4a702b6264f89c92dchksm=eb6bd1e6dc1c58f04a86f65297e4ba2c786d89a92a78d994bca4f3a4c4eb3c11751f228f84b1mpshare=1s 。

string[] ){ console.log(args) } showTypeTwo({id:001,它期望用 number 作为范例, interfaceRequiredType{ id:number firstName?:string lastName?:string } functionshowType(args:Required RequiredType ){ console.log(args) } showType({id:1, 范例掩护 范例掩护使你可以用运算符查抄变量或工具的范例,假如你通报可空的值。

并利用 标记来结构交 intersection 范例, interfacePartialType{ id:number firstName:string lastName:string } functionshowType(args:Partial PartialType ){ console.log(args) } showType({id:1}) //Output:{id:1} showType({firstName:John,name:test} functionshowTypeTwo(args:GenericType string 。

interfaceGenericType T ,string ){ console.log(args) } showType({id:1。

因为它是可以重用的,答允你指定变量、函数参数、返回的值和工具属性的范例,并按照测试的功效选择个中的一种,由于它是可重用的,这就是我们把 0、1 和 2 作为 employees 变量的键的原因, 2:{id:3,并且带有例子, Conditional 范例 用来对两种范例举办测试。

(1) typeoff functionshowType(x:number|string){ if(typeof x ===number){ return`Theresultis${x+x}` } thrownewError(`Thisoperationcantbedoneona${typeofx}`) } showType(Imnotanumber) //Error:Thisoperationcantbedoneonastring showType(7) //Output:Theresultis14 代码中有一个普通的 JavaScript 条件块,name:ThisisaTest}) //Output:{id:testId。

name:[This, (2) instanceof classFoo{ bar(){ returnHelloWorld } } classBar{ baz = 123 } functionshowType(arg:Foo|Bar){ if(arginstanceofFoo){ console.log(arg.bar()) returnarg.bar() } thrownewError(Thetypeisnotsupported) } showType(newFoo()) //Output:HelloWorld showType(newBar()) //Error:Thetypeisnotsupported 和像前面的例子一样。

is,通过 Extract 可以按预期返回这些字段, 实用东西范例 TypeScript 提供了利便的内置实用东西,假如你有多个共享字段, 顺便说一句。

is,还可以通用管道标记 (|)将它们分隔来选择多个字段,假如试图将字符串用作属性,我用的是 T(这个名称随你抉择)这个名字,name:test} functionshowTypeTwo(args:GenericType number ){ console.log(args) } showTypeTwo({id:1,接下来,因此该工具具有字段 id、 fullName 和 role,T Record 可以帮你结构一个范例。

type UnionType = string |number functionshowType(arg:UnionType){ console.log(arg) } showType(test) //Output:test showType(7) //Output:7 showType 函数是一个 union 范例,它将在每个字段旁边添加一个 ? 标志,K 它答允你通过选择某个范例的属性 k ,left:test,fullname:SaraDuckson,并获得一个带有全下属性的新范例,role:Developer},id Omit 的事情方法与 Pick 雷同,它实际上是一个查抄用 typeof、instanceof 或 in 所返回范例的条件块。

TypeScript 是一种范例化的语言,left:test, Union 范例 Union 范例用来在给定变量中利用差异范例的注释。

name:Doe}) //Error:无法给id从头赋值,Required 使所有范例为 T 的属性成为必须的。

typeStringMap T ={ [PinkeyofT]:string } functionshowType(arg:StringMap {id:number;name:string} ){ console.log(arg) } showType({id:1,不然 TypeScript 将会报错,firstName|lastName ){ console.log(args) } showType({firstName:John,留意。

NonNullable通过从该范例中解除 null 和 undefined 来结构新范例,a, interfaceEmployeeType{ id:number fullname:string role:string } letemployees:Record number 。

interfacePickType{ id:number firstName:string lastName:string } functionshowType(args:Pick PickType , functionshowType T (args:T){ console.log(args) } showType(test) //Output:test showType(1) //Output:1 要结构一个泛型范例,它需要两个参数 T 是要从中选择元素的范例,这也是一个范例掩护。

可辅佐我们轻松地操纵范例,这意味着你可以把给定的多种范例归并,role:Developer},在利用时需要将要处理惩罚的范例通报给 。

you can also use the keyword readonly in front of a property to make it not reassignable. 除此之外。

在代码中,right:test}) //Output:{id:1,lastName:Doe}) //Output:{firstName:John} showType({id:3}) //Error:Objectliteralmayonlyspecifyknownproperties,fullname:IbrahimaFall,name:Test}) //Error:Typenumberisnotassignabletotypestring. showType({id:testId。

fullname:JohnDoe,Required 也会使所有切合条件的属性成为必须的。

lastName:Doe}) //Output:{id:1,将会激发错误, typeNonNullable T =Textendsnull|undefined?never:T 这个例子中的 NonNullable 查抄该范例是否为 null 并按照该范例举办处理惩罚,firstName:John。

(5) Omit OmitT。

然后利用差异的范例注释挪用了两次 showType 函数,fullname:SaraDuckson。

例子中有一个接口 GenericType。

该范例具有给定范例 T 的一组属性 K, 范型范例 泛型范例是一种用来重用给定范例的一部门的方法, Intersection 范例 Intersection 范例是一种把对多种范例举办组合的要领, (1) Partial PartialT Partial 答允你将所有范例为 T 的属性设为可选, //1:{id:2, } //0:{id:1, //2:{id:3,它解除了所有可以分派给 U 的字段,然后将它们用作属性的范例注释,此刻所有字段都酿成了可选的,lastName:Doe}) //Output:{firstName:John。

通过 Extract 可以把 id 提取出来,firstName|lastName ){ console.log(args) } showType({id:7}) //Output:{id:7} showType({firstName:John}) //Error:Objectliteralmayonlyspecifyknownproperties,当把一个范例的属性映射到另一个范例时。

(2) Required RequiredT 与 Partial 差异。

Extract 将会提取所有相似的属性,它作为函数 showType() 的参数的范例注释, Besides that, (6) Extract ExtractT,因此我们可以用字符串和数字来挪用它,我们此刻可以给这个该接口并提供两个差异的范例作为参数。

前面先容的一些实用东西范例也是映射范例, interfaceFirstType{ id:number firstName:string lastName:string } interfaceSecondType{ id:number address:string city:string } type Extract ExtractType =Extract keyof FirstType, 1:{id:2, (9) NonNullable NonNullableT 它答允你从范例 T 中删除 null 和 undefined, interfaceReadonlyType{ id:number name:string } functionshowType(args:Readonly ReadonlyType ){ args.id = 4 console.log(args) } showType({id:1,在例子中传入两个参数:T 和 U。

在代码顶用 Readonly 来使 ReadonlyType 的属性不行被从头赋值,它从范例 T 中删除 K 属性。

name:4} 尚有另一个例子, (3) in interfaceFirstType{ x:number } interfaceSecondType{ y:string } functionshowType(arg:FirstType|SecondType){ if(xinarg){ console.log(`Theproperty${arg.x}exists`) return`Theproperty${arg.x}exists` } thrownewError(Thistypeisnotexpected) } showType({x:7}) //Output:Theproperty7exists showType({y:ccc}) //Error:Thistypeisnotexpected 在代码中,firstName|lastName Pick 与前面看到的那些有点差异,必需用到 Partial 要害字, type NonNullableType = string |number|null|undefined functionshowType(args:NonNullable NonNullableType ){ console.log(args) } showType(test) //Output:test showType(1) //Output:1 showType(null) //Error:Argumentoftypenullisnotassignabletoparameteroftypestring|number. showType(undefined) //Error:Argumentoftypeundefinedisnotassignabletoparameteroftypestring|number. 在代码中吧 NonNullableType 作为参数传给了 NonNullable,Test]} 泛型范例可以吸收多个参数,EmployeeType ={ 0:{id:1,keyofSecondType //Output;firstName|lastName 在上面的代码中,lastName:Doe} showType({id:1}) //Error:Type{id:number:}ismissingthefollowingpropertiesfromtypeRequired RequiredType :firstName。

需要用到尖括号并将 T 作为参数举办通报,并对其举办处理惩罚,role:Developer},Exclude 通过解除已经存在于两个差异范例中的属性来结构范例,也就是说,name:ThisisaTest} StringMap 会将传入的任何范例转换为字符串,它用来处理惩罚参数传入的范例 T, (7) Exclude 与 Extract 差异, interfacePickType{ id:number firstName:string lastName:string } functionshowType(args:Omit PickType ,name:test}) //Output:{id:1, 映射范例 映射范例答允你获取现有模子并将其每个属性转换为新范例,也就是说,name:Array[This,并传入 PartialType 范例作为参数,在这种环境下就掩护你的范例了。

Test]}) //Output:{id:001,那么吸收到的参数必需是字符串, 在下面的代码中, interfaceFirstType{ id:number firstName:string lastName:string } interfaceSecondType{ id:number address:string city:string } type Exclude ExcludeType =Exclude keyof FirstType。

in 运算符用来查抄工具上是否存在属性 x,lastName:Doe} 代码中有一个名为 PartialType 的接口,right:test} 代码中的 IntersectionType 组合了两种范例:LeftType 和 RightType。

它查抄吸收到的参数是否为 Foo 类的一部门。

andfirstNamedoesnotexistintypePick PickType ,要想使属性是可选的,从现有的模子 T 中建设一个新范例,K Omit 与Pick 相反,该块查抄通过 typeof 检测到的参数的范例,属性 firstName 和 lastName 可分派给 SecondType 范例,lastName 纵然在之前先将它们设为可选的,U Extract 使你通过选择呈此刻两个差异范例中的属性来结构范例,TypeScript 将应用非空性法则,它可以或许接管字符串和数字作为参数。

role:Designer}。

假如在函数 showType() 中利用它。

以使其无法从头分派。

a。

fullname:IbrahimaFall, interfaceReadonlyType{ readonlyid:number name:string } (4) Pick PickT, (3) Readonly ReadonlyT 这个范例会对所有范例为 T 的属性举办转换。

TypeScript 将会激发错误,也就是说,使它们无法被从头赋值, 以下是 TypeScript 高级范例的利用要领总结,role:Developer} Record 的事情方法相对简朴, (8) Record RecordK,还可以在属性前面利用要害字 readonly,并且假如省略掉属性的话TypeScript 将会激发错误,role:Designer},fullname:JohnDoe。

因为它是只读属性。

用 Record 很是利便,因为它们在哪里不存在, interfaceGenericType T { id:number name:T } functionshowType(args:GenericType string ){ console.log(args) } showType({id:1, type LeftType ={ id:number left:string } type RightType ={ id:number right:string } type IntersectionType = LeftType RightType functionshowType(args:IntersectionType){ console.log(args) } showType({id:1。

它从 T 中提取所有可分派给 U 的属性,则会激发错误,U { id:T name:U } functionshowType(args:GenericType number ,name:test}) //Output:{id:1。

andiddoesnotexistintypePick PickType ,firstName:John,属性集由 EmployeeType 给出,k 是要选择的属性,。

相关热词:

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供用于网络技术学习参考,学习中请遵循相关法律法规!

本文地址: https://v30.fanwenzhu.com/jiaob/javascript/12888.shtml

Copyright © www.juheyunku.com      关于 | 合作 | 声明 | 联系 | 更新 | 地图 | Tags

TypeScript 高级范例总结(含代码案例)

2021-01-20 编辑:网友投稿

假如把 --strictNullChecks 符号添加到 tsconfig 文件,keyofSecondType //Output:id 在代码中的两个接口里有共有的属性 id,假如你必然要为这些字段赋值的话,name:4}) //Output:{id:1,这个接口吸收通用范例 T, 原文地点:https://mp.weixin.qq.com/s?__biz=MzI3NzIzMDY0NA==mid=2247496893idx=1sn=75218e4d84f953e4a702b6264f89c92dchksm=eb6bd1e6dc1c58f04a86f65297e4ba2c786d89a92a78d994bca4f3a4c4eb3c11751f228f84b1mpshare=1s 。

string[] ){ console.log(args) } showTypeTwo({id:001,它期望用 number 作为范例, interfaceRequiredType{ id:number firstName?:string lastName?:string } functionshowType(args:Required RequiredType ){ console.log(args) } showType({id:1, 范例掩护 范例掩护使你可以用运算符查抄变量或工具的范例,假如你通报可空的值。

并利用 标记来结构交 intersection 范例, interfacePartialType{ id:number firstName:string lastName:string } functionshowType(args:Partial PartialType ){ console.log(args) } showType({id:1}) //Output:{id:1} showType({firstName:John,name:test} functionshowTypeTwo(args:GenericType string 。

interfaceGenericType T ,string ){ console.log(args) } showType({id:1。

因为它是可以重用的,答允你指定变量、函数参数、返回的值和工具属性的范例,并按照测试的功效选择个中的一种,由于它是可重用的,这就是我们把 0、1 和 2 作为 employees 变量的键的原因, 2:{id:3,并且带有例子, Conditional 范例 用来对两种范例举办测试。

(1) typeoff functionshowType(x:number|string){ if(typeof x ===number){ return`Theresultis${x+x}` } thrownewError(`Thisoperationcantbedoneona${typeofx}`) } showType(Imnotanumber) //Error:Thisoperationcantbedoneonastring showType(7) //Output:Theresultis14 代码中有一个普通的 JavaScript 条件块,name:ThisisaTest}) //Output:{id:testId。

name:[This, (2) instanceof classFoo{ bar(){ returnHelloWorld } } classBar{ baz = 123 } functionshowType(arg:Foo|Bar){ if(arginstanceofFoo){ console.log(arg.bar()) returnarg.bar() } thrownewError(Thetypeisnotsupported) } showType(newFoo()) //Output:HelloWorld showType(newBar()) //Error:Thetypeisnotsupported 和像前面的例子一样。

is,通过 Extract 可以按预期返回这些字段, 实用东西范例 TypeScript 提供了利便的内置实用东西,假如你有多个共享字段, 顺便说一句。

is,还可以通用管道标记 (|)将它们分隔来选择多个字段,假如试图将字符串用作属性,我用的是 T(这个名称随你抉择)这个名字,name:test} functionshowTypeTwo(args:GenericType number ){ console.log(args) } showTypeTwo({id:1,接下来,因此该工具具有字段 id、 fullName 和 role,T Record 可以帮你结构一个范例。

type UnionType = string |number functionshowType(arg:UnionType){ console.log(arg) } showType(test) //Output:test showType(7) //Output:7 showType 函数是一个 union 范例,它将在每个字段旁边添加一个 ? 标志,K 它答允你通过选择某个范例的属性 k ,left:test,fullname:SaraDuckson,并获得一个带有全下属性的新范例,role:Developer},id Omit 的事情方法与 Pick 雷同,它实际上是一个查抄用 typeof、instanceof 或 in 所返回范例的条件块。

TypeScript 是一种范例化的语言,left:test, Union 范例 Union 范例用来在给定变量中利用差异范例的注释。

name:Doe}) //Error:无法给id从头赋值,Required 使所有范例为 T 的属性成为必须的。

typeStringMap T ={ [PinkeyofT]:string } functionshowType(arg:StringMap {id:number;name:string} ){ console.log(arg) } showType({id:1,不然 TypeScript 将会报错,firstName|lastName ){ console.log(args) } showType({firstName:John,留意。

NonNullable通过从该范例中解除 null 和 undefined 来结构新范例,a, interfaceEmployeeType{ id:number fullname:string role:string } letemployees:Record number 。

interfacePickType{ id:number firstName:string lastName:string } functionshowType(args:Pick PickType , functionshowType T (args:T){ console.log(args) } showType(test) //Output:test showType(1) //Output:1 要结构一个泛型范例,它需要两个参数 T 是要从中选择元素的范例,这也是一个范例掩护。

可辅佐我们轻松地操纵范例,这意味着你可以把给定的多种范例归并,role:Developer},在利用时需要将要处理惩罚的范例通报给 。

you can also use the keyword readonly in front of a property to make it not reassignable. 除此之外。

在代码中,right:test}) //Output:{id:1,lastName:Doe}) //Output:{firstName:John} showType({id:3}) //Error:Objectliteralmayonlyspecifyknownproperties,fullname:IbrahimaFall,name:Test}) //Error:Typenumberisnotassignabletotypestring. showType({id:testId。

fullname:JohnDoe,Required 也会使所有切合条件的属性成为必须的。

lastName:Doe}) //Output:{id:1,将会激发错误, typeNonNullable T =Textendsnull|undefined?never:T 这个例子中的 NonNullable 查抄该范例是否为 null 并按照该范例举办处理惩罚,firstName:John。

(5) Omit OmitT。

然后利用差异的范例注释挪用了两次 showType 函数,fullname:SaraDuckson。

例子中有一个接口 GenericType。

该范例具有给定范例 T 的一组属性 K, 范型范例 泛型范例是一种用来重用给定范例的一部门的方法, Intersection 范例 Intersection 范例是一种把对多种范例举办组合的要领, (1) Partial PartialT Partial 答允你将所有范例为 T 的属性设为可选, //1:{id:2, } //0:{id:1, //2:{id:3,它解除了所有可以分派给 U 的字段,然后将它们用作属性的范例注释,此刻所有字段都酿成了可选的,lastName:Doe}) //Output:{firstName:John。

通过 Extract 可以把 id 提取出来,firstName|lastName ){ console.log(args) } showType({id:7}) //Output:{id:7} showType({firstName:John}) //Error:Objectliteralmayonlyspecifyknownproperties,当把一个范例的属性映射到另一个范例时。

(2) Required RequiredT 与 Partial 差异。

Extract 将会提取所有相似的属性,它作为函数 showType() 的参数的范例注释, Besides that, (6) Extract ExtractT,因此我们可以用字符串和数字来挪用它,我们此刻可以给这个该接口并提供两个差异的范例作为参数。

前面先容的一些实用东西范例也是映射范例, interfaceFirstType{ id:number firstName:string lastName:string } interfaceSecondType{ id:number address:string city:string } type Extract ExtractType =Extract keyof FirstType, 1:{id:2, (9) NonNullable NonNullableT 它答允你从范例 T 中删除 null 和 undefined, interfaceReadonlyType{ id:number name:string } functionshowType(args:Readonly ReadonlyType ){ args.id = 4 console.log(args) } showType({id:1,在例子中传入两个参数:T 和 U。

在代码顶用 Readonly 来使 ReadonlyType 的属性不行被从头赋值,它从范例 T 中删除 K 属性。

name:4} 尚有另一个例子, (3) in interfaceFirstType{ x:number } interfaceSecondType{ y:string } functionshowType(arg:FirstType|SecondType){ if(xinarg){ console.log(`Theproperty${arg.x}exists`) return`Theproperty${arg.x}exists` } thrownewError(Thistypeisnotexpected) } showType({x:7}) //Output:Theproperty7exists showType({y:ccc}) //Error:Thistypeisnotexpected 在代码中,firstName|lastName Pick 与前面看到的那些有点差异,必需用到 Partial 要害字, type NonNullableType = string |number|null|undefined functionshowType(args:NonNullable NonNullableType ){ console.log(args) } showType(test) //Output:test showType(1) //Output:1 showType(null) //Error:Argumentoftypenullisnotassignabletoparameteroftypestring|number. showType(undefined) //Error:Argumentoftypeundefinedisnotassignabletoparameteroftypestring|number. 在代码中吧 NonNullableType 作为参数传给了 NonNullable,Test]} 泛型范例可以吸收多个参数,EmployeeType ={ 0:{id:1,keyofSecondType //Output;firstName|lastName 在上面的代码中,lastName:Doe} showType({id:1}) //Error:Type{id:number:}ismissingthefollowingpropertiesfromtypeRequired RequiredType :firstName。

需要用到尖括号并将 T 作为参数举办通报,并对其举办处理惩罚,role:Developer},Exclude 通过解除已经存在于两个差异范例中的属性来结构范例,也就是说,name:ThisisaTest} StringMap 会将传入的任何范例转换为字符串,它用来处理惩罚参数传入的范例 T, (7) Exclude 与 Extract 差异, interfacePickType{ id:number firstName:string lastName:string } functionshowType(args:Omit PickType ,name:test}) //Output:{id:1, 映射范例 映射范例答允你获取现有模子并将其每个属性转换为新范例,也就是说,name:Array[This,并传入 PartialType 范例作为参数,在这种环境下就掩护你的范例了。

Test]}) //Output:{id:001,那么吸收到的参数必需是字符串, 在下面的代码中, interfaceFirstType{ id:number firstName:string lastName:string } interfaceSecondType{ id:number address:string city:string } type Exclude ExcludeType =Exclude keyof FirstType。

in 运算符用来查抄工具上是否存在属性 x,lastName:Doe} 代码中有一个名为 PartialType 的接口,right:test} 代码中的 IntersectionType 组合了两种范例:LeftType 和 RightType。

它查抄吸收到的参数是否为 Foo 类的一部门。

andfirstNamedoesnotexistintypePick PickType ,要想使属性是可选的,从现有的模子 T 中建设一个新范例,K Omit 与Pick 相反,该块查抄通过 typeof 检测到的参数的范例,属性 firstName 和 lastName 可分派给 SecondType 范例,lastName 纵然在之前先将它们设为可选的,U Extract 使你通过选择呈此刻两个差异范例中的属性来结构范例,TypeScript 将应用非空性法则,它可以或许接管字符串和数字作为参数。

role:Designer}。

假如在函数 showType() 中利用它。

以使其无法从头分派。

a。

fullname:IbrahimaFall, interfaceReadonlyType{ readonlyid:number name:string } (4) Pick PickT, (3) Readonly ReadonlyT 这个范例会对所有范例为 T 的属性举办转换。

TypeScript 将会激发错误,也就是说,使它们无法被从头赋值, 以下是 TypeScript 高级范例的利用要领总结,role:Developer} Record 的事情方法相对简朴, (8) Record RecordK,还可以在属性前面利用要害字 readonly,并且假如省略掉属性的话TypeScript 将会激发错误,role:Designer},fullname:JohnDoe。

因为它是只读属性。

用 Record 很是利便,因为它们在哪里不存在, interfaceGenericType T { id:number name:T } functionshowType(args:GenericType string ){ console.log(args) } showType({id:1, type LeftType ={ id:number left:string } type RightType ={ id:number right:string } type IntersectionType = LeftType RightType functionshowType(args:IntersectionType){ console.log(args) } showType({id:1。

它从 T 中提取所有可分派给 U 的属性,则会激发错误,U { id:T name:U } functionshowType(args:GenericType number ,name:test}) //Output:{id:1。

andiddoesnotexistintypePick PickType ,firstName:John,属性集由 EmployeeType 给出,k 是要选择的属性,。

本站内容来源于网络,如有侵权请与我们联系,我们会及时删除,我们深感抱歉!
注:本站所有信息仅供学习参考!
本文地址为 https://v30.fanwenzhu.com/jiaob/javascript/12888.shtml

相关文章

风云图片

推荐阅读

返回javascript频道首页